package com.itheima.reggin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.itheima.reggin.common.R;
import com.itheima.reggin.mapper.OrdersMapper;
import com.itheima.reggin.dto.OrdersDto;
import com.itheima.reggin.entity.*;

import com.itheima.reggin.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private UserService userService;

    //开启事务
    @Transactional
    @Override
    public R<String> submit(Orders orders, HttpSession session) {
        //获取登录用户id
        Long userId = (Long) session.getAttribute("user");
        //获取登录用户信息
        User user = userService.getById(userId);

        //判断地址是否存在
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        if (addressBook == null) {
            return R.error("设置的地址不存在,请重新设置地址");
        }

        //判断购物车是否为空
        LambdaQueryWrapper<ShoppingCart> shoppingCartLqw = new LambdaQueryWrapper<>();
        shoppingCartLqw.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(shoppingCartLqw);
        if (shoppingCarts == null) {
            return R.error("购物车为空");
        }
        //获得订单id
        long orderId = IdWorker.getId();
        //将订单id放入session中
        session.setAttribute("orderId", orderId);
        //获得总金额,使用原子操作,防止出现安全问题
        AtomicInteger amount = new AtomicInteger(0);
        //将购物车中的数据添加到订单明细表中
        List<OrderDetail> orderDetails = shoppingCarts.stream().map(shoppingCart -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);//订单id
            orderDetail.setImage(shoppingCart.getImage());//img路径名
            orderDetail.setDishFlavor(shoppingCart.getDishFlavor());//口味
            orderDetail.setDishId(shoppingCart.getDishId());//菜品id
            orderDetail.setSetmealId(shoppingCart.getSetmealId());//套餐id
            orderDetail.setName(shoppingCart.getName());//菜品或套餐名称
            orderDetail.setNumber(shoppingCart.getNumber());
            amount.addAndGet(shoppingCart.getAmount().multiply(BigDecimal.valueOf(shoppingCart.getNumber())).intValue());
            orderDetail.setAmount(shoppingCart.getAmount());
            return orderDetail;
        }).collect(Collectors.toList());
        //将数据添加到订单明细表中
        orderDetailService.saveBatch(orderDetails);
        //添加订单信息
        orders.setNumber(String.valueOf(orderId));  //订单号
        orders.setStatus(1);//状态
        orders.setUserId(userId);//用户id
        orders.setOrderTime(LocalDateTime.now());//下单时间
        orders.setCheckoutTime(LocalDateTime.now());//付款时间
        orders.setAmount(BigDecimal.valueOf(amount.intValue()));//总金额
        orders.setPhone(addressBook.getPhone());//接收人电话
        orders.setAddress(
                (addressBook.getProvinceName() != null ? addressBook.getProvinceName() : "") +
                        (addressBook.getCityName() != null ? addressBook.getCityName() : "") +
                        (addressBook.getDistrictName() != null ? addressBook.getDistrictName() : "") +
                        addressBook.getDetail()
        );//接收地址
        orders.setUserName(user.getName());//下单人名称
        orders.setConsignee(addressBook.getConsignee());//收货人名称
        //保存订单
        this.save(orders);
        //清除购物车数据
        shoppingCartService.remove(shoppingCartLqw);
        return R.success("下单成功");
    }

    @Transactional
    @Override
    public R<PageDto<OrdersDto>> userPage(PageDto<OrdersDto> pageDto, HttpSession session) {
        Long userId = (Long) session.getAttribute("user");
        Page<Orders> page = new Page<>(pageDto.getPage(), pageDto.getPageSize());
        LambdaQueryWrapper<Orders> ordersLqw = new LambdaQueryWrapper<>();
        ordersLqw.eq(Orders::getUserId,userId)
                .orderByDesc(Orders::getOrderTime);
        this.page(page,ordersLqw);
        List<Orders> ordersList = page.getRecords();
        List<OrdersDto> ordersDtos = ordersList.stream().map(orders -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(orders, ordersDto);
            //通过订单号查询订单明细
            LambdaQueryWrapper<OrderDetail> orderDetailLqw = new LambdaQueryWrapper<>();
            orderDetailLqw.eq(OrderDetail::getOrderId, orders.getNumber());
            List<OrderDetail> orderDetails = orderDetailService.list(orderDetailLqw);
            ordersDto.setOrderDetails(orderDetails);
            return ordersDto;
        }).collect(Collectors.toList());
        pageDto.setRecords(ordersDtos);
        pageDto.setTotal((int) page.getTotal());
        return R.success(pageDto);
    }
}
